<?php

namespace common\model\sell66;

use common\db\Sell66;
use think\Log;

class OutTradeDetail extends Sell66
{
	protected $table = 'out_trade_detail';

	public static function insertOutTradeDetail($outTradeId, $userId, $appId, array $invs)
	{
		$botInvIds = [];
		foreach ($invs as $inv) {
			$botInvIds[] = $inv['bot_inv_id'];
		}

		$botInvs = BotInv::getLockBotInvByUserId($userId, $appId, $botInvIds);
		if (count($botInvs) != count($botInvIds)) {
			Log::record('query lock bot inv failed, user_id : '.$userId);
			return false;
		}

		$details = [];
		foreach ($botInvs as $botInv) {
			$details[] = array(
				'out_trade_id' => $outTradeId,
				'bot_inv_id' => $botInv['bot_inv_id'],
				'app_id' => $botInv['app_id'],
				'o_id' => $botInv['o_id'],
				'class_id' => $botInv['class_id'],
				'instance_id' => $botInv['instance_id'],
				'market_hash_name' => $botInv['market_hash_name'],
				'market_name' => $botInv['market_name'],
			);
		}

		$result = static::insertAll($details);
		if (!$result) {
			Log::warning('insert out trade deatils failed, details: '.json_encode($details));
			return false;
		}

		$result = BotInv::updateLockByUserId($userId, $appId, $botInvIds);
		if (!$result) {
			Log::warning('update lock bot inv failed, user_id: '.$userId.', details: '.json_encode($botInvIds));
			return false;
		}

		return true;
	}
}